package com.yjd.bi.etl.funds;

import com.yjd.bi.etl.funds.service.FundsUserBalanceService;
import com.yjd.bi.fund.model.BiUserBalanceListModel;
import com.yjd.comm.base.concurrent.task.DefaultTaskDispose;
import com.yjd.comm.base.concurrent.task.ITaskHandler;
import com.yjd.comm.base.concurrent.task.ITaskItem;
import com.yjd.comm.util.DateUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.job.BaseJob;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by yjd-wap on 2017/4/17.
 */
public class UserBalanceStatisticsJob extends BaseJob {

    @Resource
    private FundsUserBalanceService fundsUserBalanceService;

    @Override
    protected boolean doExecute() throws Exception {
        Long currTime = FrameUtil.getTime();

        Date stDate = DateUtil.addDay(DateUtil.timestampToDate(DateUtil
                .dateStringToTimestamp(DateUtil.timestampToDateString(
                        FrameUtil.getTime(), DateUtil.PATTERN_yyyyMMdd),
                        DateUtil.PATTERN_yyyyMMdd)), -1);
        //当前月份
        int currtMonth = Integer.parseInt(DateUtil.format(stDate,
                DateUtil.PATTERN_yyyyMM));
        //当前日期
        int currtDate = Integer.parseInt(DateUtil.format(stDate,
                DateUtil.PATTERN_yyyyMMdd));
        Long user_start = 100000L;//本次开始数据时间
        int month_start = 201312;//初始化月份
        int date_start = 20131221;//初始化日期
        Map maxInfo = fundsUserBalanceService.getMaxInfo();
        if (maxInfo != null && maxInfo.size() > 0) {
            if (Integer.parseInt(maxInfo.get("run_date").toString()) >= currtDate) {
                logger.info("已经是最新的数据日期");
                return true;
            }

            if (maxInfo.get("date_status") != null && "0".equals(maxInfo.get("date_status"))) {
                //当天未跑完
                month_start = Integer.parseInt(maxInfo.get("run_month").toString());
                date_start = Integer.parseInt(maxInfo.get("run_date").toString());
                user_start = Long.parseLong(maxInfo.get("start_userid").toString());
            } else {
                //当天已跑完
                String date_over = maxInfo.get("run_date").toString();
                Date next_date = DateUtil.addDay(DateUtil.parseDate(date_over, DateUtil.PATTERN_yyyyMMdd), 1);
                month_start = Integer.parseInt(DateUtil.format(next_date, DateUtil.PATTERN_yyyyMM));
                date_start = Integer.parseInt(DateUtil.format(next_date, DateUtil.PATTERN_yyyyMMdd));
            }
        }

        do {
            Long start = FrameUtil.getTime(DateUtil.parseDate(date_start + "", DateUtil.PATTERN_yyyyMMdd)) + 86399;
            Long max_userid = fundsUserBalanceService.getMaxUserIdByRegDate(start);
            fundsUserBalanceService.insertyfundsRunRecord(month_start, date_start, max_userid, user_start, FrameUtil.getTime(null));
            fundsUserBalanceService.delBalanceMonth(month_start, date_start, user_start);
            do {
                Long endUserid = 0L;
                if (user_start.intValue() + 15000 > max_userid.intValue()) {
                    endUserid = max_userid;
                } else {
                    endUserid = user_start + 15000;
                }

                //执行每天按人生成的记录
                Map<String, Object> handleMap = fundsUserBalanceService.getHandleUserList(user_start, endUserid);
                if (handleMap != null && handleMap.size() > 0) {
                    Long currMax = Long.parseLong(handleMap.get("lastUserId").toString());
                    List<List<Long>> allUserList = new ArrayList<>();

                    for (int i = 0;i<30 ;i++){
                        if(handleMap.get("list"+i) != null){
                            allUserList.add((List<Long>) handleMap.get("list"+i));
                        }
                    }

                    boolean overFlag = false;
                    if (currMax.intValue() == max_userid.intValue()) {
                        overFlag = true;
                    }

                    if (allUserList != null) {
                        generatePartUserBalance(date_start, month_start, allUserList, user_start, overFlag);
                    }
                    user_start = endUserid;
                } else {
                    if (user_start.intValue() + 15000 < max_userid.intValue()) {
                        user_start = user_start + 15000;
                    } else {
                        user_start = max_userid;
                    }
                }

                if (user_start.intValue() == max_userid.intValue()) {
                    fundsUserBalanceService.updatefundsRunRecord(month_start, date_start, user_start, FrameUtil.getTime(null), 1);
                }

            } while (user_start < max_userid);

            //生成平台每天的余额
            fundsUserBalanceService.insertYjdPfBalance(month_start, date_start);

            Date next_date = DateUtil.addDay(DateUtil.parseDate(date_start + "", DateUtil.PATTERN_yyyyMMdd), 1);
            month_start = Integer.parseInt(DateUtil.format(next_date, DateUtil.PATTERN_yyyyMM));
            date_start = Integer.parseInt(DateUtil.format(next_date, DateUtil.PATTERN_yyyyMMdd));
            user_start = 100000L;
            if (date_start > currtDate) {
                return true;
            }
        } while (true);

    }


    @SuppressWarnings("unchecked")
    private void generatePartUserBalance(final int currDate, final int month, List<List<Long>> list, Long run_userid, final boolean overFlag)
            throws Exception {
        final Long statiisticsDate = FrameUtil.getTime(DateUtil.parseDate(currDate + "", DateUtil.PATTERN_yyyyMMdd)) + 86399;
        final List balanceList = Collections.synchronizedList(FrameUtil.newArrayList());

        List<UserListItem> taskItems = new ArrayList<UserListItem>();
        if (list != null) {
            for (List<Long> userItemList : list) {
                BiUserBalanceListModel model = new BiUserBalanceListModel();
                model.setUseridList(userItemList);
                taskItems.add(new UserListItem(model));
            }
        } else {
            return;
        }
        long starttime = System.currentTimeMillis();
        final Result flag = Result.getInstance(true);
        new DefaultTaskDispose(true, 30).taskDipose(taskItems,
                new ITaskHandler<BiUserBalanceListModel>() {
                    @Override
                    public void dispose(ITaskItem<BiUserBalanceListModel> taskItems) {
                        //如果有失败的，其他的直接不处理了
                        if (!flag.isSuccess()) {
                            return;
                        }
                        if (taskItems == null || taskItems.getItem() == null) {
                            return;
                        }
                        try {
                            balanceList.addAll(fundsUserBalanceService.queryUserBalance(taskItems.getItem().getUseridList(), statiisticsDate));
                        } catch (Exception e) {
                            flag.setSuccess(false);
                            logger.error("异常信息是：" + e);
                        }
                    }
                });
        //如果有失败的，抛出异常，让job下次再处理
        if (!flag.isSuccess()) {
            FrameUtil.throwBaseException1("根据用户id生成每天月失败!");
        }
        fundsUserBalanceService.insertBatchUserBalanceByMonth(month, currDate, run_userid, balanceList, overFlag);

    }

    @Override
    protected String getJobType() {
        return UserBalanceStatisticsJob.class.getName();
    }

    static class Result {
        boolean isSuccess;

        static Result getInstance(boolean isSuccess) {
            Result result = new Result();
            result.isSuccess = isSuccess;
            return result;
        }

        public boolean isSuccess() {
            return isSuccess;
        }

        public void setSuccess(boolean isSuccess) {
            this.isSuccess = isSuccess;
        }
    }

    public class UserListItem implements ITaskItem<BiUserBalanceListModel> {

        private BiUserBalanceListModel userBalanceListModel;

        public UserListItem(BiUserBalanceListModel userBalanceListModel) {
            this.userBalanceListModel = userBalanceListModel;
        }

        @Override
        public BiUserBalanceListModel getItem() {
            return userBalanceListModel;
        }
    }
}
